package org.lmw.note;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.exception.DbException;
import com.norbsoft.typefacehelper.TypefaceHelper;

public class Act_Edit extends FragmentActivity implements OnClickListener{

	TextView tv_date;
	EditText et_text;
	ImageButton btn_save,btn_del;
	Note note = null;
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.act_edit);
		TypefaceHelper.typeface(this);
		initView();
	}

	private void initView() {
		tv_date=(TextView)findViewById(R.id.tv_date);
		et_text = (EditText) findViewById(R.id.et_text);
		btn_save = (ImageButton) findViewById(R.id.btn_save);
		btn_del=(ImageButton)findViewById(R.id.btn_del);
		btn_save.setOnClickListener(this);
		btn_del.setOnClickListener(this);
		tv_date.setText(date2Str());
		if (null!=getIntent().getExtras()) {
			//修改、查看
			note = new Gson().fromJson(getIntent().getExtras().getString("objStr"), Note.class);
			et_text.setText(note.getText());
			et_text.setSelection(note.getText().length());
			tv_date.setText(note.getCreateTime());
		}
	}
	
	public static String date2Str(){
		String style="yyyy年MM月dd日 HH:mm:ss";
		SimpleDateFormat formatter = new SimpleDateFormat(style,Locale.getDefault());
		return formatter.format(new Date());
	}
	
	public void back(View v){
		onBackPressed();
	}

	@Override
	public void onClick(View v) {
		if(v==btn_save){
			try {
				if(note==null)
				note = new Note();
				String data=et_text.getText().toString().trim();
				if(data.length()>0){
					note.setText(data);
					note.setCreateTime(date2Str());
					App.db.saveOrUpdate(note);
				}
				setResult(RESULT_OK); 
				finish();
		} catch (DbException e) { 
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), "保存失败",Toast.LENGTH_SHORT).show();
		}
		}
		if(v==btn_del){
			Dialog dialog = new AlertDialog.Builder(this).
		    setTitle("提示").
		    setMessage("删除这条记录").

		    setNegativeButton("取消", new DialogInterface.OnClickListener() {
		     @Override
		     public void onClick(DialogInterface dialog, int which) {
		     }
		    }).
		    setPositiveButton("确定", new DialogInterface.OnClickListener() {
			     @Override
			     public void onClick(DialogInterface dialog, int which) {
						if(note!=null){
							try {
								App.db.delete(note);
							} catch (DbException e) {
								e.printStackTrace();
							}
						}
						setResult(RESULT_OK); 
						finish();
			     }
			    }).
		    create();
			dialog.show();
		}
	}

}
